package com.frame.hibernate;

import java.util.HashMap;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.frame.database.operate.DataBaseType;
import com.wframe.framework.spring.SpringContextHolder;

/**
 * @Title: 系统
 * @Description:
 * @Copyright: Copyright (c) 2014
 * @Company:
 * @author 王海锋
 * @CreatedTime:2014-4-15 上午10:07:03
 * @version 1.0
 */

public class HibernateFactory {
    private static final String DEFALUT_CON="Hibernate_defalut";
    private static ThreadLocal<Session> sessionL=new ThreadLocal<Session>();


    private static Map<String,HibernateConfig> factoryMap=new HashMap<String,HibernateConfig>();

    public void factoryMapDefalutPut(HibernateConfig config){
        factoryMap.put(DEFALUT_CON, config);
    }

    public void factoryMapPut(String name,HibernateConfig config){
        factoryMap.put(name, config);
    }
    public static Session getSession(String ftg) throws Exception{
//        if(ftg==null)ftg=DEFALUT_CON;
//        if(hiconfig==null)
//            throw new Exception("没有定义"+ftg+"数据库的连接!");
        Session s = sessionL.get();
        SessionFactory sessionFactory= (SessionFactory)SpringContextHolder.getBean("sessionFactory");
        // Open a new Session, if this Thread has none yet
        if (s == null && sessionFactory!=null) {
            s = sessionFactory.openSession();

            sessionL.set(s);
        }

        return s;
    }

    public static Session getSession() throws Exception{
        return getSession(DEFALUT_CON);
    }
    public static Session openSession(String ftg) throws Exception{
        return null;
    }
    public static Session openSession() throws Exception{
        return openSession(DEFALUT_CON);
    }
    public static DataBaseType getDataBaseType(String ftg) throws Exception{
//        HibernateConfig hiconfig=null;
//        if(ftg==null)hiconfig=factoryMap.get(DEFALUT_CON);
//        else hiconfig=factoryMap.get(ftg);
//        if(hiconfig==null)
//            throw new Exception("没有定义"+ftg+"数据库的连接!");
        return DataBaseType.getDataBaseType("mysql");
    }
    public static void closeSession(String ftg) throws Exception {
        Session s = (Session) sessionL.get();

        if (s != null)
            s.close();
        sessionL.set(null);
    }
    public static void closeSession() throws Exception {
        closeSession(DEFALUT_CON);
    }
}
